import html2canvas from "html2canvas";
/**
 * 获取图片文件的宽高信息
 * @param file 图片文件对象（如 input[type="file"] 选择的文件）
 * @returns Promise<{ width: number, height: number }>
 */
export const getImageWH = (file:any): Promise<any> => {
  return new Promise((resolve) => {
    const img: any = new Image();
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      img.src = this.result;
    };
    img.onload = () => {
      resolve({
        width: img.width,
        height: img.height,
      });
    };
  });
};

// import QRCode from 'qrcodejs2'
/** 获取图片的宽高比例
 * @param width
 * @param height
 * @returns
 */
export const imageLongWideProportion = (
  width: string | number,
  height: string | number
): number[] => simplifyAspectRatio(`${width}:${height}`); // 简化的宽高比字符串
// 求最大公约数的函数（欧几里得算法）
const greatestCommonDivisor = (a: any, b: any): any =>
  b === 0 ? a : greatestCommonDivisor(b, a % b);

const simplifyAspectRatio = (ratioString: string) => {
  const [width, height]: any[] = ratioString.split(":");
  const gcd = greatestCommonDivisor(width, height);
  const simplifiedWidth = width / gcd;
  const simplifiedHeight = height / gcd;
  return [simplifiedWidth, simplifiedHeight];
};
/** 将base64转换为图片
 * @param base64
 * @returns
 */
export const base64ToImg = (base64: any): Promise<any> => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = base64;
    img.onload = function () {
      resolve(img);
    };
    img.onerror = function (e) {
      reject(e);
    };
  });
};
/** 压缩图片
 *
 * @param base64 图片的base64格式
 * @param mx 触发压缩的图片最大宽度限制
 * @param mh 触发压缩的图片最大高度限制
 */
// export const compressImg = (base64: any, mx: number, mh: number): Promise<any> => {
//     return new Promise(async (resolve) => {
//         const img = await base64ToImg(base64)
//         const canvas = document.createElement('canvas')
//         const context: any = canvas.getContext('2d')
//         const targetWidth = mx
//         const targetHeight = mh
//         canvas.width = targetWidth
//         canvas.height = targetHeight
//         context.drawImage(img, 0, 0, targetWidth, targetHeight)
//         canvas.toBlob((blob) => { resolve(blob) }, 'image/jpeg')
//     })
// }
export const compressImg = (
  base64: any,
  mx: number,
  mh: number
): Promise<any> => {
  return new Promise((resolve) => {
    base64ToImg(base64).then((img) => {
      const canvas = document.createElement("canvas");
      const context: any = canvas.getContext("2d");
      const targetWidth = mx;
      const targetHeight = mh;
      canvas.width = targetWidth;
      canvas.height = targetHeight;
      context.drawImage(img, 0, 0, targetWidth, targetHeight);
      canvas.toBlob((blob) => {
        resolve(blob);
      }, "image/jpeg");
    });
  });
};

/**
 * 将base64字符串（非dataURL，仅base64编码）转为图片URL
 * @param imgUrl base64字符串
 * @returns Promise<string> 图片的URL
 */
export const getBase64ToImgUrl = (imgUrl: any) => {
  return new Promise((resolve) => {
    const byteCharacters = atob(imgUrl);
    const byteNumbers = new Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    const blob = new Blob([byteArray], { type: "image/jpeg" });
    //blob-->url
    let binaryData = [];
    binaryData.push(blob);
    let url = URL.createObjectURL(new Blob(binaryData));
    resolve(url);
  });
};

/**
 * 根据图片元素id下载图片
 * @param id 图片元素的id
 */
export const dwonImg = (id: string, fileName: string) => {
  const img: any = document.getElementById(id); // 获取要下载的图片
  const url = img.src; // 获取图片地址
  const a = document.createElement("a"); // 创建一个a节点插入的document
  const event = new MouseEvent("click"); // 模拟鼠标click点击事件
  a.download = fileName; // 设置a节点的download属性值
  a.href = url; // 将图片的src赋值给a节点的href
  a.dispatchEvent(event); // 触发鼠标点击事件
};

/**
 * 根据图片元素id下载图片
 * @param id 图片元素的id
 */
export const dwonImgByHtml2canvas = async (ref: any, fileName: string) => {
  await html2canvas(ref, {
    backgroundColor: "#fff",
  }).then((canvas: any) => {
    let url = canvas.toDataURL("image/png");
    let images = url;
    const a = document.createElement("a");
    a.href = images;
    a.download = `${fileName}.png`;
    a.click();
  });
};

const imgList = ["jpg", "jpeg", "png", "JPG", "JPEG", "PNG", "wav"];
/**
 * 预览图片或下载文件。
 * 如果文件扩展名为图片类型，则在新标签页打开，否则直接下载。
 * @param url 文件或图片的url
 */
export const previewImage = (url: string) => {
  const link = document.createElement("a");
  const falg = imgList.some((item) =>  url.substring(url.lastIndexOf(".") + 1, url.length) === item);
  if (falg == true) {
    link.target = "_blank";
  }

  link.setAttribute("download", "");
  link.href = url;
  link.click();
};

/**
 * 翻转图片 Blob（水平或垂直镜像）
 * @param blob 原始图片的 Blob 对象
 * @param flipX 水平翻转，1为不翻转，-1为水平镜像（默认1）
 * @param flipY 垂直翻转，1为不翻转，-1为垂直镜像（默认1）
 * @returns Promise<Blob> 翻转后的图片 Blob（JPEG 格式）
 *
 * 示例：
 * // 水平翻转
 * flipBlob(blob, -1, 1)
 * // 垂直翻转
 * flipBlob(blob, 1, -1)
 * // 水平+垂直翻转
 * flipBlob(blob, -1, -1)
 */
export const flipBlob=(blob: Blob, flipX = 1, flipY = 1): Promise<Blob>=> {
  return new Promise((resolve) => {
    const img = new Image()
    img.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      const ctx = canvas.getContext('2d')!
      ctx.translate(flipX === -1 ? img.width : 0, flipY === -1 ? img.height : 0)
      ctx.scale(flipX, flipY)
      ctx.drawImage(img, 0, 0)
      canvas.toBlob((result) => resolve(result!), 'image/jpeg')
    }
    img.src = URL.createObjectURL(blob)
  })
}

/**
 * 合成带二维码的图片（如生成海报）
 * @param imgUrl 背景图片基础路径
 * @param qrUrl 二维码内容或跳转地址
 * @param data 配置对象（包含二维码宽高、位置、背景图片名等）
 * @param _thisq 用于渲染二维码的DOM节点
 * @param _thisOut 输出合成图片的img节点
 * @returns Promise<boolean> 合成成功返回true，失败返回false
 */
// 参数说明
// const imgUrl = 'https://example.com/'; // 背景图片基础路径
// const qrUrl = 'https://your-qr-content.com'; // 二维码内容或跳转地址
// const data = {
//     materialsUrl: 'bg.jpg', // 背景图片文件名
//     qrWidth: 120,           // 二维码宽度
//     qrHight: 120,           // 二维码高度
//     qrX: 100,               // 二维码在画布上的X坐标
//     qrY: 200                // 二维码在画布上的Y坐标
// };
// const _thisq = document.getElementById('qrcode');
// const _thisOut = document.getElementById('outputImg');
// generateImg(imgUrl, qrUrl, data, _thisq, _thisOut)
// export const generateImg = (imgUrl:string, qrUrl:string, data:any, _thisq:any, _thisOut:any) => {
//     return new Promise((resolve, reject) => {
//         try {
//             const param = {
//                 width: data.qrWidth,
//                 height: data.qrHight,
//                 text: qrUrl, // 设置二维码内容或跳转地址
//                 render: 'table', // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
//                 correctLevel: QRCode.CorrectLevel.Q
//             }
//             // eslint-disable-next-line no-new
//             new QRCode(_thisq, param)
//             const myImage = new Image()
//             myImage.src = imgUrl + data.materialsUrl + '?time=' + new Date().valueOf() // 背景图片  你自己本地的图片或者在线图片
//             myImage.setAttribute('crossOrigin', 'Anonymous')
//             myImage.onload = () => {
//                 try {
//                     const canvas = document.createElement('canvas')
//                     canvas.width = myImage.width
//                     canvas.height = myImage.height
//                     const context:any = canvas.getContext('2d')
//                     context.rect(0, 0, canvas.width, canvas.height)
//                     context.fillStyle = '#fff'
//                     context.fill()
//                     context.drawImage(myImage, 0, 0)
//                     const myImage2 = new Image()
//                     myImage2.setAttribute('crossOrigin', 'Anonymous')
//                     const imgs = _thisq.getElementsByTagName('img')
//                     myImage2.src = imgs[0].getAttribute('src') // 你自己本地的图片或者在线图片
//                     myImage2.onload = function () {
//                         try {
//                             context.drawImage(myImage2, data.qrX, data.qrY, data.qrWidth, data.qrHight)
//                             const base64 = canvas.toDataURL('image/png') // "image/png" 这里注意一下
//                             const img = _thisOut
//                             img.setAttribute('src', base64)
//                             resolve(true)
//                         } catch (e) {
//                             console.log(e)
//                             reject(false)
//                         }
//                     }
//                 } catch (e) {
//                     console.log(e)
//                     reject(false)
//                 }
//             }
//         } catch (e) {
//             console.log(e)
//             reject(false)
//         }
//     })
// }
